package com.pethospital.filter;

import com.pethospital.entity.User;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证过滤器
 * Login Authentication Filter
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class LoginFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 获取请求URI
        String requestURI = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        
        // 排除不需要登录验证的路径
        if (isExcludedPath(requestURI, contextPath)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 获取session
        HttpSession session = httpRequest.getSession(false);
        User currentUser = null;
        
        if (session != null) {
            currentUser = (User) session.getAttribute("currentUser");
        }
        
        // 检查用户是否已登录
        if (currentUser == null) {
            // 未登录，重定向到登录页面
            httpResponse.sendRedirect(contextPath + "/pages/common/login.jsp");
            return;
        }
        
        // 检查用户权限
        if (requestURI.contains("/admin/") && !"admin".equals(currentUser.getUserType())) {
            // 普通用户访问管理员页面，重定向到无权限页面
            httpResponse.sendRedirect(contextPath + "/pages/common/unauthorized.jsp");
            return;
        }
        
        // 检查用户状态
        if (!"active".equals(currentUser.getStatus())) {
            // 用户被禁用，清除session并重定向到登录页面
            session.invalidate();
            httpResponse.sendRedirect(contextPath + "/pages/common/login.jsp?error=disabled");
            return;
        }
        
        // 验证通过，继续执行
        chain.doFilter(request, response);
    }
    
    /**
     * 判断是否为排除路径（不需要登录验证的路径）
     * 
     * @param requestURI 请求URI
     * @param contextPath 上下文路径
     * @return boolean 是否为排除路径
     */
    private boolean isExcludedPath(String requestURI, String contextPath) {
        // 移除上下文路径
        String path = requestURI.substring(contextPath.length());
        
        // 排除的路径列表
        String[] excludedPaths = {
            "/pages/common/login.jsp",
            "/pages/common/register.jsp",
            "/pages/common/error.jsp",
            "/pages/common/unauthorized.jsp",
            "/user/login",
            "/user/register",
            "/user/logout",
            "/css/",
            "/js/",
            "/images/",
            "/index.jsp"
        };
        
        for (String excludedPath : excludedPaths) {
            if (path.startsWith(excludedPath)) {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public void destroy() {
        // 清理资源
    }
}
